package com.funkyfurrymonkey.load ;
import openfl.net.URLRequest;
import openfl.display.BitmapData;
import openfl.display.Bitmap;
import openfl.display.Loader;
import openfl.events.ErrorEvent;
import openfl.events.Event;
import openfl.events.IOErrorEvent;
import openfl.events.ProgressEvent;

/**
 * ...
 * @author Marcos Martinez
 */
class ImageLoader extends Loader
{

	private var m_cUrlRequest:URLRequest;
	public var m_nTotalBytes:Int;
	public var m_nCurrentBytesLoaded:Int;
	
	public function new(sPath:String) 
	{
		super();
		m_nTotalBytes = 0;
		m_nCurrentBytesLoaded = 0;
		m_cUrlRequest = new URLRequest(sPath);
	
		this.contentLoaderInfo.addEventListener(Event.COMPLETE,OnComplete);
		this.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, OnError);
		this.contentLoaderInfo.addEventListener(ProgressEvent.PROGRESS, onChange);
		
	}
	
	public function start():Void
	{
		this.load(m_cUrlRequest);		
	}
	
	private function OnComplete(ev:Event):Void
	{
		//trace(ev);
		removeOnFinish();
		var bmd:BitmapData = cast(content, Bitmap).bitmapData;
		onComplete(bmd);
	}
	
	private function OnError(ev:Event):Void
	{
		trace(ev);
		removeOnFinish();
	}
	
	dynamic public function onComplete(cImage:BitmapData) { }
	
	private function onChange(ev:Event):Void
	{
		if (m_nTotalBytes == 0)
		{
			m_nTotalBytes = this.contentLoaderInfo.bytesTotal;
			onStart(m_nTotalBytes);
		}
		m_nCurrentBytesLoaded = this.contentLoaderInfo.bytesLoaded;
		onProgress(m_nCurrentBytesLoaded);
			
	}
	
	dynamic public function onProgress(nBytesLoaded:Int) { };
	dynamic public function onStart(nTotalBytes:Int) { };
	private function removeOnFinish():Void
	{
		this.contentLoaderInfo.removeEventListener(Event.COMPLETE, OnComplete);
		this.contentLoaderInfo.removeEventListener(ProgressEvent.PROGRESS, onChange);
		this.contentLoaderInfo.removeEventListener(IOErrorEvent.IO_ERROR, OnError);
	}
	
	public function stop():Void
	{
		this.close();
		this.unloadAndStop(true);
		removeOnFinish();
		//this  = null;
	}
}